import os
import json
from datetime import datetime
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from models import SessionLocal, Book, Word  # 确保 models.py 可以被正确导入

BASE_DIR = 'doc/project_output'


def insert_words_from_json():
    """
    遍历指定目录下的JSON文件，解析单词数据并插入到数据库。
    """
    print("开始单词插入流程...")

    # 获取 BASE_DIR 下所有直接的子目录
    # 假设每个子目录（如 '1', '2', '3'）包含一个 word.json
    subdirs = [os.path.join(BASE_DIR, d) for d in os.listdir(BASE_DIR) if os.path.isdir(os.path.join(BASE_DIR, d))]

    if not subdirs:
        print(f"在 '{BASE_DIR}' 目录下没有找到任何子目录。请确保您的 project_output 结构正确。")
        return

    for subdir_path in subdirs:
        json_file_path = os.path.join(subdir_path, 'word.json')

        if not os.path.exists(json_file_path):
            print(f"跳过文件夹 '{os.path.basename(subdir_path)}': '{json_file_path}' 文件未找到。")
            continue

        print(f"正在处理文件: {json_file_path}...")

        db: Session = SessionLocal()  # 为每个JSON文件打开一个新的数据库会话
        try:
            with open(json_file_path, 'r', encoding='utf-8') as f:
                words_data = json.load(f)
        except json.JSONDecodeError as e:
            print(f"错误：解码JSON文件 '{json_file_path}' 失败: {e}")
            db.close()
            continue
        except Exception as e:
            print(f"错误：读取文件 '{json_file_path}' 失败: {e}")
            db.close()
            continue

        book_id = words_data['word_level_id']
        # 检查单词是否已存在，防止重复插入
        existing_book = db.query(Book).filter(
            Book.id == book_id
        ).first()

        if not existing_book:
            print("创建书本")
            book = Book(
                id=book_id,
                name="研究生",
                description="cs"
            )
            db.add(book)
            db.commit()

        # 检查单词是否已存在，防止重复插入
        word = words_data["word"]
        existing_word = db.query(Word).filter(
            Word.word == word
        ).first()

        if  existing_word:
            print("单词已存在，跳过插入")
            continue
        # 创建新的 Word 对象
        new_word = Word(
            book_id=book_id,
            word=word,
            accent=words_data["accent"],
            mean_cn=words_data["mean_cn"],
            mean_en=words_data["mean_en"],
            sentence=words_data["sentence"],
            sentence_trans=words_data["sentence_trans"],
            word_etyma=words_data["word_etyma"],
            created_at=datetime.utcnow(),
            updated_at=datetime.utcnow()
        )
        db.add_all([new_word])
        db.commit()

        db.close()  # 关闭当前文件的数据库会话

    print("单词插入流程完成。")


if __name__ == "__main__":
    insert_words_from_json()
